<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               ref="crud"
               v-model="form"
               :permission="permissionList"
               :before-open="beforeOpen"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template #menu-left="{}">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   v-if="this.permission.manage.dept.delete"
                   plain
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template #menu="scope">
        <el-button
            link
          icon="el-icon-circle-plus-outline"
          size="small"
          @click.stop="handleAdd(scope.row,scope.index)"
          v-if="userInfo.roles.some(k => k.roleAlias.includes('admin'))"
        >新增子项
        </el-button>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
  import {deptApi} from "/src/api/system/dept";
  import website from '/src/config/website';
  import {mapState} from "pinia";
  import {useUserStore} from "/src/store/modules/user.js";
  import {avueVaildData} from "/src/utils/validate.js";
  import permission from "@/directives/permission/index.js";

  export default {
    data() {
      return {
        form: {},
        selectionList: [],
        loading: true,
        query: {},
        page: {
          pageSize: 100,
          currentPage: 1,
          total: 0
        },
        option: {
          searchShow: true,
          searchMenuSpan: 6,
          tip: false,
          tree: true,
          border: true,
          index: true,
          selection: true,
          viewBtn: true,
          menuWidth: 300,
          defaultExpandAll: true,
          column: [
            {
              label: "部门名称",
              prop: "deptName",
              search: true,
              rules: [{
                required: true,
                message: "请输入部门名称",
                trigger: "blur"
              }]
            },
            {
              label: "所属租户",
              prop: "tenantId",
              type: "tree",
              addDisplay: false,
              editDisplay: false,
              viewDisplay: website.tenantMode,
              span: 24,
              dicData: [],
              props: {
                label: "tenantName",
                value: "tenantId"
              },
              hide: true,
              // hide: !website.tenantMode,
              search: website.tenantMode,
              rules: [{
                required: true,
                message: "请输入所属租户",
                trigger: "click"
              }]
            },
            {
              label: "部门全称",
              prop: "fullName",
              search: true,
              rules: [{
                required: true,
                message: "请输入部门全称",
                trigger: "blur"
              }]
            },
            {
              label: "上级部门",
              prop: "parentId",
              dicData: [],
              type: "tree",
              hide: false,
              props: {
                label: "title"
              },
              defaultExpandAll: true,
              rules: [{
                required: false,
                message: "请选择上级部门",
                trigger: "click"
              }]
            },
            {
              label: "排序",
              prop: "sort",
              type: "number",
              value: 1,
              rules: [{
                required: false,
                message: "请输入排序",
                trigger: "blur"
              }]
            },
            {
              label: "备注",
              prop: "remark",
              span: 24,
              hide: true,
              rules: [{
                required: false,
                message: "请输入备注",
                trigger: "blur"
              }]
            }
          ]
        },
        data: []
      };
    },
    computed: {
      permission() {
        return permission
      },
      ...mapState(useUserStore, ["userInfo", "permission"]),
      permissionList() {
        return {
          addBtn: avueVaildData(this.permission.manage.dept.add, false),
          viewBtn: avueVaildData(this.permission.manage.dept.view, false),
          delBtn: avueVaildData(this.permission.manage.dept.delete, false),
          editBtn: avueVaildData(this.permission.manage.dept.edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      handleAdd(row) {
        console.log("row", row)
        console.log("row", this.$refs.crud)
        console.log("row",  this.$refs.crud.option.column)
        // this.$refs.crud.value.parentId = row.id;
        this.$refs.crud.option.column.filter(item => {
          if (item.prop === "parentId") {
            console.log("item.prop",item.prop)
            item.value = row.id;
            item.addDisabled = true;
          }
        });
        this.$refs.crud.rowAdd();
      },
      rowSave(row, done, loading) {
        deptApi.create(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {
        deptApi.update(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return deptApi.remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return deptApi.remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          deptApi.getDept(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        deptApi.getPage(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          let data = res.data;
          this.page.total = data.count;
          this.data = data.data;
          this.loading = false;
          deptApi.getDeptTree().then(res => {
            console.log(res)
            const column = this.findObject(this.option.column, "parentId");
            column.dicData = res.data.data;
            deptApi.getTenantList().then(res => {
              const column1 = this.findObject(this.option.column, "tenantId");
              column1.dicData = res.data.data;
            })
          });
        });
      }
    }
  };
</script>

<style>
</style>
